/**
 @Name    工具脚本
 */
var LIG_DATA;
layui.define(['jquery', 'layer', 'table', 'laytpl','admin', 'view', 'conf', 'util'], function (exports) {
    "use strict";
    POPUP_DATA = {}

    var $ = layui.jquery;

    var laytpl = layui.laytpl
        , layTable = layui.table
        , form = layui.form
        , layer = layui.layer
        , pLayer = parent.layui.layer ? parent.layui.layer : layer
        , admin = layui.admin
        , view = layui.view
        , conf = layui.conf
        , util = layui.util;

    /*
    if (parent.parent.layui.layer) {
        pLayer = parent.parent.layui.layer;
    } else if (parent.layui.layer) {
        pLayer = parent.layui.layer;
    } else {
        pLayer = layer;
    }
    */

    var msg_zh_CN = {
        info: '提示',
        ok: '知道了',
        sureDelete: '确定删除吗？',
        save: '保 存',
        confirm: '确 定',
        cancel: '取 消',
        success: '操作成功',
        delSuccess: '删除成功',
        choose: '请选择'
    };
    var msg_en_US = {
        info: 'Info',
        ok: 'OK',
        sureDelete: 'Are you sure to delete?',
        save: 'Save',
        confirm: 'Confirm',
        cancel: 'Cancel',
        success: 'Success',
        delSuccess: 'Success',
        choose: 'choose...'
    };
    var lang = {};
    lang.get = function (key) {
        var msg = admin.sessionData()['lang'];
        if (msg == 'en_US') return msg_en_US[key];
        return msg_zh_CN[key];
    };

    var lig = {

        /**弹出层（遮盖）工具类 A**/
        alert: function (message) {
            return layer.alert(message, {title: lang.get('info'), icon: 6, btn: [lang.get('ok')]});
        },
        confirm: function (message, opt, success, error) {
            if (typeof opt == 'undefined') {
                opt = {};
            }
            if (typeof opt.title == 'undefined' || opt.title == '') {
                opt.title = lang.get('info');
            }
            opt.icon = 3;
            return pLayer.confirm(message, opt, success, error);
        },
        msg: function (message) {
            layer.msg(message, {icon: 0, time: 1500});
        },
        error: function (message) {
            pLayer.alert(message, {title: lang.get('info'), icon: 5, btn: [lang.get('ok')]});
        },
        success: function (message) {
            if (typeof message == 'undefined' || message == null || message == '') {
                message = lang.get('success');
            }
            layer.msg(message, {icon: 1, time: 1500, offset: 't'});
        },
        fail: function (message) {
            pLayer.alert(message, {icon: 5});
        },

        //var loadIndex;
        load: function() {
            var loadIndex = layer.load();
        },
        unload: function() {
            layer.closeAll('loading');
        },
        open: function (html, option) {
            var _self = this;

            var _width = '50%'
                , _height = '80%'
                , _title = ''
                , _type = 1
                , _success = function () {}
                , _end = function () {};

            if (typeof option != 'undefined') {
                if (typeof option.title != 'undefined' && option.title != '') {
                    _title = option.title;
                }
                if (typeof option.width != 'undefined' && option.width != '' && option.width != _width) {
                    _width = option.width.indexOf('%') < 0 ? option.width + 'px' : option.width;
                }
                if (typeof option.height != 'undefined' && option.height != '' && option.height != _height) {
                    _height = option.height.indexOf('%') < 0 ? option.height + 'px' : option.height;
                }
                if (typeof option.type != 'undefined' && option.type != '') {
                    _type = option.type;
                }
                if (typeof option.end != 'undefined' && typeof option.end == 'function') {
                    _end = option.end;
                }
                if (typeof option.success != 'undefined' && typeof option.success == 'function') {
                    _success = option.success;
                }
            }

            if ($('#layer_return_data').length <= 0) {
                $(document.body).append('<input type="hidden" id="layer_return_data">');
            }

            return layer.open({
                type: _type
                , offset: 'auto'
                , closeBtn: 1
                //,anim: 2
                , title: _title
                , area: [_width, _height] //宽高
                , content: html
                , success: function (layero, index) {
                    _self.filter($('.layui-layer'));
                    form.render();
                    _success(layero, index);
                }
                , end: function () {
                    var _data = _self.getLayerReturnData();
                    _end(_data);
                }
            });
        }
        , dialog: function (options) {
            POPUP_DATA = options.data || {}

            var _self = this, _layerIndex;

            var _save = function (data) {
                var reqData = data;
                if (typeof options.onSave != 'undefined') {
                    reqData = options.onSave(data);
                    if (reqData == false) {
                        return;
                    }
                }

                _self.ajaxpost({
                    url: options.saveUrl
                    , data: reqData
                    , success: function (res) {
                        if (typeof options.dataTable != 'undefined') {
                            options.dataTable.reloadTable();
                        }

                        _self.close(_layerIndex);
                        _self.success('保存成功');

                        if (typeof options.onCompleted != 'undefined') {
                            options.onCompleted(res);
                        }
                    }
                });
            };

            var fill = function(content) {
                var _defOptions = {
                    type: 1,
                    offset: 'auto',
                    closeBtn: 1
                    ,btn: [lang.get('save'), lang.get('cancel')]
                    ,btnAlign: 'r'
                    , title: ''
                    , area: ['50%', '70%'] //宽高
                    , content: ''
                    , success: function (layero, index) {
                        _self.filter($('.layui-layer'));

                        form.render();

                        if (typeof options.onOpened != 'undefined') {
                            options.onOpened();
                        }

                        $('[lay-filter="lig-saveForm"]').append('<div type="button" style="display: none;" lay-submit lay-filter="lig-save"></div>');
                        form.on('submit(lig-save)', function (data) {
                            _save(data.field);
                            return false;
                        });

                    },
                    yes: function (index, layero) {
                        $('[lay-filter="lig-save"]').trigger('click');
                        return false;
                    }
                    , end: function () {
                    }
                };
                // 将2的值合并到1，同key时 默认2将会覆盖1的值
                $.extend(_defOptions, options);

                _defOptions.content = content;
                _layerIndex = layer.open(_defOptions);
                return _layerIndex;
            }

            if (typeof options.url == 'undefined' || url == '') {
                return fill(options.content);
            }

            view.loadHtml(conf.views + options.url, function(res) {
                //var htmlElem = $('<div>' + res.html + '</div>');

                //if (_defOptions.title === undefined) {
                    //_defOptions.title = htmlElem.find('title').text() || '信息';
                    //if (_defOptions.title) htmlElem.find('title').remove();
                //}

                //_self.open(htmlElem.html(), _defOptions);
                return fill(res.html);
            });

        }
        , importData(options) {
            var _self = this, _layerIndex;
            var opt = {
                title: '批量导入',
                url: 'setting/dataImport',
                width: '40%',
                height: '50%',
                onOpened: function() {
                }
            };
            // 将2的值合并到1，同key时 默认2将会覆盖1的值
            $.extend(opt, options);
            view.loadHtml(conf.views + opt.url, function(res) {
                _self.ajaxget({
                    url: 'setting/params/value/' + options.tplCode,
                    success: function(result) {
                        options.tplUrl = result.data;

                        var htmlElem = $('<div>' + res.html + '</div>');
                        htmlElem.find('#tplUrl').val(result.data);
                        htmlElem.find('#importUrl').val(options.importUrl);
                        _layerIndex = _self.open(htmlElem.html(), opt);
                    }
                });
            });
        }
        , choose: function (options) {
            var _self = this, _layerIndex;
            var _defOptions = {
                offset: 'auto'
                , closeBtn: 1
                , title: ''
                , height: '100px' //宽高
                , success: function (layero, index) {
                    if (typeof options.onOpened != 'undefined') {
                        options.onOpened();
                    }
                }
            };

            // 将2的值合并到1，同key时 默认2将会覆盖1的值
            $.extend(_defOptions, options);
            view.loadHtml(conf.views + _defOptions.url, function(res) {
                var htmlElem = $('<div>' + res.html + '</div>');

                if (_defOptions.title === undefined) {
                    _defOptions.title = htmlElem.find('title').text() || '信息';
                    if (_defOptions.title) htmlElem.find('title').remove();
                }
                //_defOptions.content = htmlElem.html();

                _layerIndex = _self.open(htmlElem.html(), _defOptions);
            });
        }
        , remove: function (options) {
            var _self = this;

            var _layerIndex = _self.confirm(lang.get('sureDelete'),
                {
                    btn: [lang.get('confirm'), lang.get('cancel')]
                }
                , function () {
                    _self.ajaxpost({
                        url: options.url,
                        data: options.data,
                        success: function (result) {
                            _self.success(lang.get('delSuccess'));
                            if (typeof options.completed != 'undefined') {
                                options.completed();
                            }
                            _self.closeLayer(_layerIndex);
                        }
                    });
                }
                , function () {
                    // 取消操作
                    if (typeof options.cancel != 'undefined') {
                        options.cancel();
                    }
                }
            );
            return _layerIndex;
        }
        /**
         * 删除弹出层
         * @param index
         */
        , close: function (index) {
            if (typeof index == 'undefined') {
                index = layer.getFrameIndex(window.name);
            }
            layer.close(index);
        }
        /**
         * 删除父级的弹出层
         * @param index
         */
        , closeLayer: function (index) {
            if (typeof index == 'undefined') {
                index = pLayer.getFrameIndex(window.name);
            }
            pLayer.close(index);
        }
        , setLayerReturnData: function (data) {
            if (typeof data != 'undefined' && typeof data == 'object') {
                data = JSON.stringify(data);
            }
            return parent.$('#layer_return_data').val(data);
        }
        , getLayerReturnData: function () {
            var _self = this;

            var _data = $('#layer_return_data').val();
            if (_self.isJSON(_data)) {
                return $.parseJSON(_data);
            }
            return '';
        }
        /**弹出层（遮盖）工具类 Z**/



        /**table工具类 A**/
        /**封装layui grid**/
        , table: function (options, extend) {
            var _self = this, _entity = typeof extend != 'undefined' && typeof extend.entity != 'undefined' ? extend.entity : '';

            if (typeof options == 'undefined') {
                return;
            }

            if (typeof options.height == 'undefined') {
                options.height = '';
            }

            if (typeof options.page == 'undefined') {
                options.page = {theme: '#409EFF'};//开启分页,
            }
            options.request = {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            };
            options.response = {
                statusName: 'code' //数据状态的字段名称，默认：generator
                , statusCode: 'success' //成功的状态码，默认：0
                , msgName: 'message' //状态信息的字段名称，默认：msg
                , countName: 'total' //数据总数的字段名称，默认：count
                , dataName: 'items' //数据列表的字段名称，默认：data
            };
            options.parseData = function (res) { //res 即为原始返回的数据
                var _code = res.code, _total, _items;

                if (_code == 'logout') {
                    admin.logout();
                    return null;
                }

                if (res.data) {
                    _total = res.data.total ? res.data.total : 0;
                    _items = res.data.items ? res.data.items : null;
                }

                return {
                    "code": _code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "total": _total, //解析数据长度
                    "items": _items //解析数据列表
                };
            }
            // 表格数据加载完成
            var defDone = typeof options.done != 'undefined' ? options.done : function() {};
            options.done = function(res, curr, count) {
                _self.filter($(options.elem).next());
                _self.filterAction($(options.elem).next());
                defDone(res, curr, count);
            }

            options.limit = 20;
            options.id = _entity + 'Id';
            options.defaultToolbar = ['filter', 'print'];
            options.url = conf.requestUrl + options.url;
            options.where = _self.form2JSON('[lay-filter="lig-' + _entity + '-searchform"]');
            //options.skin = 'line';
            //options.even = true;
            var _table = layTable.render(options);

            if (typeof options.toolEvent != 'undefined'
                && typeof options.toolEvent == 'function') {
                table.on('tool', function (obj) {
                    options.toolEvent(obj);
                });
            }

            //监听表格复选框选择
            if (typeof options.checkboxEvent != 'undefined'
                && typeof options.checkboxEvent == 'function') {
                table.on('checkbox(' + options.id + ')', function (obj) {
                    options.checkboxEvent(obj);
                });
            }

            var _reloadTable = function (opt) {
                var _dataJSON = _self.form2JSON('[lay-filter="lig-' + _entity + '-searchform"]');
                _table.reload({
                    where: _dataJSON
                    , done: function (res, curr, count) {
                        if (typeof options != 'undefined') {
                            if (typeof options.done != 'undefined') {
                                options.done(res, curr, count);
                            }
                        }
                        _self._tableExtend(_table, extend);
                    }
                });
            }
            _table.reloadTable = _reloadTable;


            if (arguments.length == 2) {
                _self._tableExtend(_table, extend);
            }

            return _table;
        },
        _tableExtend: function (dataTable, extend) {
            var _self = this
                , _layerIndex
                , _entity = extend.entity;
                //, _selector = dataTable.config.elem.selector
                //, _table  = _selector.substring(_selector.indexOf('lig'), _selector.length - 2);

            extend.dataTable = dataTable;

            var _cancel = function () {
                $('.ligui-cancel').unbind('click').bind('click', function () {
                    _self.close(_layerIndex);
                });
            };

            // 保存
            var _save = function (url) {
                // 监听提交
                form.on('submit(lig-save)', function (data) {
                    // 单击之后提交按钮不可选,防止重复提交
                    var DISABLED = 'layui-btn-disabled';
                    // 增加样式
                    $('.ligui-layer-btn0 ligui-save').addClass(DISABLED);
                    // 增加属性
                    $('.ligui-layer-btn0 ligui-save').attr('disabled', 'disabled');

                    _self.ajaxpost({
                        url: url
                        , data: data.field
                        , success: function () {
                            dataTable.reloadTable();
                            _self.close(_layerIndex);
                            _self.success();
                        }
                        ,error:function(){
                            layer.msg(result.message, {icon: 5});
                            $('.ligui-layer-btn0 ligui-save').removeClass(DISABLED);
                            $('.ligui-layer-btn0 ligui-save').removeAttr('disabled');
                        }
                    });
                    return false;

                });
            };

            // 删除
            var _remove = function () {
                var _datas = layTable.checkStatus(_entity + 'Id').data
                    , _length = _datas.length;
                if (_length <= 0) {
                    return;
                }

                var _ids = '';
                $.each(_datas, function (i, item) {
                    _ids += "," + item[extend.primaryField];
                });
                if (_ids != '') {
                    _ids = _ids.substring(1);
                }
                _self.remove({
                    url: extend.removeUrl
                    , data: {ids: _ids}
                    , completed: function () {
                        dataTable.reloadTable();
                    }
                });
            };

            // 获取详情
            var _get = function (id, callbaock) {
                var _data = {};

                var _url = extend.getUrl,
                    _p = '{' + extend.primaryField + '}';

                if (_url.indexOf(_p) > -1) {
                    _url = _url.replace(_p, id);
                } else {
                    _data[extend.primaryField] = id;
                }

                _self.ajaxget({
                    url: _url
                    , data: _data
                    , success: function (result) {
                        callbaock(result.data);
                    }
                });
            };

            // 新增
            $('[lay-filter="lig-' + _entity + '-add"]').unbind('click').bind('click', function () {
                if (typeof extend.mode != 'undefined' && extend.mode == 'dialog') {
                    extend.title = extend.addTitle;
                    extend.content = extend.addContent;
                    extend.saveUrl = extend.addUrl;
                    extend.onOpened = extend.onAddOpened;
                    _layerIndex = _self.dialog(extend);
                } else {
                    _layerIndex = _self.open(extend.addContent,
                    {
                        type: 1
                        , title: extend.addTitle
                        , height: extend.addHeight
                        , success: function () {

                            if (typeof extend.onAddOpened != 'undefined') {
                                extend.onAddOpened();
                            }

                            _save(extend.addUrl);
                            _cancel();
                        }
                    });
                }
            });

            // 查询
            $('[lay-filter="lig-' + _entity + '-search"]').unbind('click').bind('click', function () {
                dataTable.reloadTable();
            });
            // 重置
            $('[lay-filter="lig-' + _entity + '-reset"]').unbind('click').bind('click', function () {
               $('[lay-filter="lig-' + _entity + '-searchform"]')[0].reset();
               //$('[lay-filter="lig-' + _entity + '-searchform"]').reset();
               dataTable.reloadTable();
            });

            // 导出
            // $('[lay-filter="lig-' + _entity + '-excel"]').click(function() {
            //     _self.export('[lay-filter="lig-' + _entity + '-searchform"]', optexcel');
            // });

            // 行工具条
            layTable.on('tool(lig-' + _entity + '-table)', function (obj) {
                var _item = obj.data;

                switch (obj.event) {
                    case 'lig-modify':

                        _get(_item[extend.primaryField], function (data) {
                            laytpl(extend.modifyContent).render(data, function (html) {
                                if (typeof extend.mode != 'undefined' && extend.mode == 'dialog') {
                                    extend.title = extend.modifyTitle;
                                    extend.content = html;
                                    extend.saveUrl = extend.modifyUrl;
                                    extend.onOpened = extend.onModifyOpened;
                                    _layerIndex = _self.dialog(extend);
                                } else {
                                    _layerIndex = _self.open(html,
                                    {
                                        type: 1
                                        , title: extend.modifyTitle
                                        , height: extend.modifyHeight
                                        , success: function () {
                                            if (typeof extend.onModifyOpened != 'undefined') {
                                                extend.onModifyOpened();
                                            }
                                            _save(extend.modifyUrl);
                                            _cancel();
                                        }
                                    });
                                }
                            });
                        });
                        break;
                    case 'lig-get':
                        if (typeof extend.onGet != 'undefined' && extend.onGet(_item) == true) {
                            _get(_item[extend.primaryField], function (data) {
                                laytpl(extend.getContent).render(data, function (html) {
                                    _layerIndex = _self.open(html,
                                        {
                                            type: 1
                                            , title: extend.getTitle
                                            , width: extend.getWidth
                                            , height: extend.getHeight
                                            , success: function () {
                                                if (typeof extend.onGetOpened != 'undefined') {
                                                    extend.onGetOpened();
                                                }
                                                _cancel();
                                            }
                                        });
                                });
                            });
                        }
                        break;
                    case 'lig-delete':
                        _self.remove({
                            url: extend.removeUrl
                            , data: {ids: _item[extend.primaryField]}
                            , completed: function () {
                                dataTable.reloadTable();
                            }
                        });
                        break;
                    case 'lig-detail':
                        _get(_item[extend.primaryField], function (data) {
                            laytpl(extend.detailContent).render(data, function (html) {
                                layer.open({
                                    type: 1,
                                    title: false,
                                    content: html,
                                    closeBtn: 0,
                                    area: ['40%', '100%'],
                                    offset: 'auto',
                                    success: function(layero){
                                        layero.css({'left': 'auto','right': '0'});
                                        if (typeof extend.onDetailOpened != 'undefined') {
                                            extend.onDetailOpened();
                                        }
                                    }
                                });
                            });
                        });
                        break;
                    default:
                        if (typeof extend.onTool != 'undefined') {
                            extend.onTool(obj);
                        }
                        break;
                };
            });

            // 删除
            $('[lay-filter="lig-' + _entity + '-remove"]').unbind('click').bind('click', function () {
                _remove();
            });
            // 表格工具条
            /*
            layTable.on('toolbar(lig-table)', function (obj) {
                switch (obj.event) {
                    case 'lig-remove':
                        // 删除
                        _remove();
                        break;
                    default:
                        if (typeof extend.onTool != 'undefined') {
                            extend.onTool(obj);
                        }
                        break;
                };
            });
            */

            $('.layui-icon-export').unbind('click').bind('click', function () {
            });
        },
        selectedRows: function (tableId) {
            return table.checkStatus(tableId);
        },
        /**table工具类 Z**/

        /**ajax工具类 A**/
        ajaxpost: function (option) {
            var _self = this;

            option.type = 'post';
            _self.ajaxaction(option);
        },
        ajaxget: function (option) {
            var _self = this;

            option.type = 'get';
            _self.ajaxaction(option);
        },
        ajaxput: function (option) {
            var _self = this;

            option.type = 'put';
            _self.ajaxaction(option);
        }
        , ajaxdelete: function (option) {
            var _self = this;

            option.type = 'delete';
            _self.ajaxaction(option);
        }
        , ajaxaction: function (option) {
            var _self = this;

            var _async = true;
            if (typeof option.async != 'undefined') {
                _async = option.async;
            }
            var _data = typeof option.data != 'undefined' ? option.data : {};
            view.request({
                type: option.type,
                dataType: 'json',
                async: _async,
                url: option.url,
                data: _data,
                //contentType: 'application/json;charset=UTF-8',
                success: function (result) {
                    _self.unload();
                    _self.ajaxresult(result, option);
                },
                error: function () {
                    _self.unload();
                }
            });
        }
        , ajaxresult: function(result, option) {
            var _self = this;

            if (result.code == conf.response.statusCode.ok) {
                if ($.isFunction(option.success)) option.success(result);
                else _self.success();
            } else if (result.code == conf.response.statusCode.noPermission) {
                _self.error('无权限');
            } else {
                if ($.isFunction(option.fail)) option.fail(result);
                else _self.error(result.message);
            }
        }
        /**ajax工具类 Z**/

        /** 事件绑定 A**/

        /**
         * 绑定键盘事件
         * @param callback    回调函数
         */
        , keydown: function (callback) {
            $(document).keydown(function (event) {
                callback(event.keyCode);
            });
        }
        /** 事件绑定 Z**/

        , export: function(formEle, url) {
            $(formEle).attr('method', 'post');
            $(formEle).attr('action', conf.requestUrl + url);
            $(formEle).submit();
        }

        , isJSON: function (jsonStr) {
            if (typeof jsonStr == 'string') {
                try {
                    var obj = JSON.parse(jsonStr);
                    return true;
                } catch (e) {
                    return false;
                }
            }
        }

        ,getDataJSON: function($ele) {
            var _dataJSON = {};
            $ele.find('input,select,textarea').each(function () {
                var _this = $(this)
                    , _n = _this.attr('name')
                    , _v = _this.val();

                if (typeof _n == 'undefined') {
                    return true;
                }

                _dataJSON[_n] = _v;
            });
            return _dataJSON;
        }

        , form2JSON: function (ele) {
            var _self = this;
            return _self.getDataJSON($(ele));
        }

        , getFormData : function(ele){
            var data = {};
            var results = $(ele).serializeArray();
            $.each(results,function(index,item){
                //文本表单的值不为空才处理
                if(item.value && $.trim(item.value)!=""){
                    if(!data[item.name]){
                        data[item.name]=item.value;
                    }else{
                        //name属性相同的表单，值以英文,拼接
                        data[item.name]=data[item.name]+','+item.value;
                    }
                }
            });
            return data;
        },
        selectData: function(url, ele, selected) {
            selected = typeof selected == 'undefined' ? true : false;
            $(ele).html('<option value=""></option>');
            var _selectValue = $(ele).attr('lay-data');
            lig.ajaxget({
                url: url,
                success: function (result) {
                    if (result.data) {
                        $.each(result.data, function (i, _it) {
                            var _selected = '';
                            if (selected && typeof _selectValue != 'undefined' && _selectValue != '' && _selectValue == _it.value) {
                                _selected = 'selected';
                            }
                            $(ele).append('<option value="' + _it.value + '" ' + _selected+ '>' + _it.text + '</option>');
                        });
                        form.render();
                    }
                }
            });
        },
        loadSelect: function(url, ele, selected) {
            if (typeof selected == 'undefined') {
                selected = true;
            }
            $(ele).html('<option value=""></option>');
            var _selectValue = $(ele).attr('lay-data');
            lig.ajaxget({
                url: url,
                success: function (result) {
                    if (result.data) {
                        $.each(result.data, function (i, _it) {
                            var _selected = '';
                            if (selected && typeof _selectValue != 'undefined' && _selectValue != '' && _selectValue == _it.dictCode) {
                                _selected = 'selected';
                            }
                            $(ele).append('<option value="' + _it.dictCode + '" ' + _selected+ '>' + _it.dictName + '</option>');
                        });
                        form.render();
                    }
                }
            });
        },
        loadSelectDict: function(constant, ele, selected) {
            var _self = this;
            _self.loadSelect('setting/dict/list/constant/' + constant, ele, selected);
        },
        selectDictByParentCode: function(parentCode, ele, selected) {
            var _self = this;
            _self.loadSelect('setting/dict/list/parent-code/' + parentCode, ele, selected);
        },
        selectSplb: function(formFilter) {
            var _self  = this,
                splbEle = '[lay-filter="' + formFilter + '"] select[name="splb"]',
                splb2Ele = '[lay-filter="' + formFilter + '"] select[name="splb2"]',
                splb3Ele = '[lay-filter="' + formFilter + '"] select[name="splb3"]',
                splbData = $(splbEle).attr('lay-data'), splb2Data = $(splb2Ele).attr('lay-data');

            _self.loadSelectDict('sku_splb', splbEle);
            // if (splbData) {
            //     _self.selectDictByParentCode(splbData, splb2Ele);
            // }
            // if (splb2Data) {
            //     _self.selectDictByParentCode(splb2Data, splb3Ele);
            // }
            //
            // form.on('select(lig-splb)', function(data){
            //     _self.selectDictByParentCode(data.value, splb2Ele, false);
            //
            //     $(splb3Ele).html('<option value=""></option>');
            // });
            // form.on('select(lig-splb2)', function(data){
            //     _self.selectDictByParentCode(data.value, splb3Ele, false);
            // });
        },
        selectCustomerList: function(ele) {
            var _selectValue = $(ele).attr('lay-data');
            lig.ajaxget({
                url: 'pd/customer/select' ,
                success: function (result) {
                    if (result.data) {
                        $.each(result.data, function (i, _it) {
                            var _selected = '';
                            if (typeof _selectValue != 'undefined' && _selectValue != '' && _selectValue == _it.customerCode) {
                                _selected = 'selected';
                            }
                            $(ele).append('<option value="' + _it.customerCode + '" ' + _selected+ '>' + _it.nameCn + '</option>');
                        });
                        form.render();
                    }
                }
            });
        }
        ,getSelected: function(code, value) {
            if (code == value) {
                return 'selected';
            }
            return '';
        },
        toBooleString: function (code) {
            return code == 1 ? '是' : '否';
        }
        ,toDateString: function(time, format) {
            if (typeof time == 'undefined' || time == null || time == 'null' || time == '') {
                return '';
            }
            return util.toDateString(time, format);
        },
        // 补零函数
        doHandleZero: function(zero) {
            var date = zero;
            if (zero.toString().length == 1) {
                date = "0" + zero;
            }
            return date;
        },
        // 获取当前年-月-日
        getDateNow: function() {
            var _self = this;
            var myDate = new Date();
            var tYear = myDate.getFullYear()
            var tMonth = myDate.getMonth()
            var tDay = myDate.getDate()
            tMonth = _self.doHandleZero(tMonth + 1)
            tDay = _self.doHandleZero(tDay)
            return tYear + "-" + tMonth + "-" + tDay
        },

        // 获取前一天年-月-日
        getDateNow: function() {
            var _self = this;
            var myDate = new Date();
            var tYear = myDate.getFullYear()
            var tMonth = myDate.getMonth()
            var tDay = myDate.getDate()
            tMonth = _self.doHandleZero(tMonth + 1)
            tDay = _self.doHandleZero(tDay)
            return tYear + "-" + tMonth + "-" + tDay
        },

        // date 代表指定的日期，格式：2018-09-27
        // day 传-1表始前一天，传1表始后一天
        // JS获取指定日期的前一天，后一天
        getNextDate: function(day) { 
        　　var dd = new Date();
        　　dd.setDate(dd.getDate() + day);
        　　var y = dd.getFullYear();
        　　var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
        　　var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
        　　return y + "-" + m + "-" + d;
        },

        filter: function (element) {
            if (admin.sessionData()['lang-label']) {
                var label = admin.sessionData()['lang-label'];
                element.find('[lig-lang]').each(function () {
                    var value = $(this).attr('lig-lang');
                    $(this).text(label[value])
                });
            }
        },
        filterAction: function (container) {
            if (admin.sessionData()['action']) {
                var data = admin.sessionData()['action'];
                $.each(data, function (i, it) {
                    var ele = container.find('[lay-filter="lig-' + it.code + '"]')
                    if (it.auth) {
                        ele.text(it.name)
                    } else {
                        ele.remove()
                    }
                });
            }
        },

        reqUrl: function(url) {
            return conf.requestUrl + url;
        },
        radioHtml: function(opts) {
            var html = '';
            $.each(opts.item, function(i, it) {
                var checked = '';
                if (typeof opts.checkedValue != 'undefined' && opts.checkedValue == it.value) {
                    checked = 'checked';
                }
                html += '<input type="radio" name="' + it.name + '" value="' + it.value + '" title="' + it.title + '" ' + checked + '>';
            });
            return html;
        },
        boolRadioHtml: function(name, checkedValue) {
            console.log(checkedValue);
            var self = this;
            var opts = {};
            opts.checkedValue = checkedValue;
            opts.item = [
                {name: name, title: '否', value: '0'},
                {name: name, title: '是', value: '1'}
            ];
            return self.radioHtml(opts);
        }

    };

    // 暴露接口
    exports('lig', lig);
});